package org.yangspring.samples.mvc.simple;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.yangspring.samples.mvc.domain.BooksTPerC;
import org.yangspring.samples.mvc.service.BooksTPerCService;

import java.util.List;

import static java.lang.System.out;

/**
 * Created by whyang on 2017/06/19.
 */

@Controller
//@RestController
@RequestMapping("/book")
public class BooksController {
    private static final Logger logger = LoggerFactory.getLogger(BooksController.class);

    /*private BooksTPerCService bookService;

    @Autowired
    @Qualifier(value = "bookService")
    public void setBookService(BooksTPerCService service){
        this.bookService = service;
    }*/

    @Autowired
//    @Resource(name = "bookService")
    private BooksTPerCService bookService;


    @RequestMapping(value = "/list", method = RequestMethod.GET)
    public String listBook(Model model){
        logger.warn("\n\nbooking --- list\n\n");

        model.addAttribute("book001", new BooksTPerC());

        List<BooksTPerC> boooks = this.bookService.listBook();
        logger.warn("\n\nboooks Quantity:\t" + boooks.size() + "\n\n");

        model.addAttribute("listBook", boooks);
//        return "listBook";
        return "book";
    }


    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public String addBook(@ModelAttribute("book001") BooksTPerC book){
        logger.warn("\n\n\tBook Controller add\n\n");
        this.bookService.addBook(book);
        return "addBook";
    }


    @RequestMapping("/remove/{id}")
    public String removePerson(@PathVariable("id") long id){
        logger.warn("\n\n\tBook Controller remove\n\n");
        this.bookService.removeBook(id);
        return "redirect:/book";
    }

    @RequestMapping("/edit/{id}")
    public String editPerson(@PathVariable("id") long id, Model model){
        model.addAttribute("book", this.bookService.getBookById(id));
        model.addAttribute("listBook", this.bookService.listBook());
        return "book";
    }


}
